2

Is it possible to return values in async code?

For example, I have some async code that looks like this:

async function(a,b){
    fetch('url'+b)
    .then(res) => res.json())
    .then(data) => obj = data
    .then() => {
        //writes to html just fine
        var x = obj.jsonvalue;
        var y = obj.otherjsonvalue;

        //create an array of these values
        var z = [x,y];
        return z;
}

Obviously, when it returns 'z' I can see that it's only returning a promise. Is there a way to return the actual values of z, ie the array?

Birdman333
  • 73
  • 2
  • 9

1 Answers1

1

Maybe you're looking for something like this example:

var promise = new Promise(function (resolve){
  resolve(1 + 1);
});

var result = promise.then(function (x) {
  return x + 1;
});

(async function () {
    var number = await result;
    
    console.log(number); // 3
}());

We can use await inside an asynchronous function with this syntax:

(async function () {
    // await some task...
}());

or

(async () => {
    // await some task...
})();

Since result is a promise, we can await it to get the result directly.

Tân
  • 1
  • 15
  • 56
  • 102