1

I'm getting more and more confortable with the asyncawait library.

If I'm correct, this:

var doSth = async function() {
  var asyncResult = await promiseReturningFunction();
  subFunction(asyncResult);
};

is equivalent to:

var doSth = function() {
  promiseReturningFunction().then(function(asyncResult) {
    subFunction(asyncResult);
  });
};

But what if the callback has two arguments .then(function(asyncResult1, asyncResult2) {})?

In some other languages, I'd write:

  var asyncResult1, asyncResult2 = await promiseReturningFunction();

but I can't do this in JS, can I? Does await returns an array? The first argument?

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
  • 1
    The asyncawait library and the upcoming `async/await` are two different things. They may work in a very similar way, but you should clarify which one you are talking about. Even though you are linking to the library, your example doesn't seem to use the library. – Felix Kling Feb 25 '16 at 17:49
  • Are you using the experimental async/await transpiler, or that fiber-based library? – Bergi Feb 25 '16 at 17:54

3 Answers3

8

I can't do this in JS, can I?

No, you can't. Promises fulfill with only a single value.

JavaScript doesn't have tuples, but you can use an array for that. With destructuring, you can make it look almost like in those other languages:

async function promiseReturningFunction() {
    await …;
    …
    return [result1, result2];
}

// elsewhere (in an async function):
var [asyncResult1, asyncResult2] = await promiseReturningFunction();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

You can easily use the destructuring on a bunch of promises like that:

var [r1, r2, r3] = await Promise.all([p1, p2, p3]);

or

var promises = [p1(), p2(), p3()];
$q.all(promises)
  .then(function ([p1Result, p2Result, p3Result]) {
      // ...
  });

So you will have:

async function doSth() {
    var [asyncResult1, asyncResult1] = await promiseReturningFunction();
    var asyncLastResult = await subFunction(asyncResult1);

    return asyncLastResult;
}

doSth();
julien bouteloup
  • 3,022
  • 22
  • 16
0

Promises can only pass one argument to the fulfillment callback. As Benjamin Gruenbaum writes:

[...] Just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.

(Here is the section in the Promises/A+ specification)

So your case with two arguments doesn't occur in JavaScript (at least not with standard promise implementations). Just use an array or an object (depending on your data structure).

Community
  • 1
  • 1
nils
  • 25,734
  • 5
  • 70
  • 79