简体   繁体   中英

javascript: don't return until a promise resolves

I need to wait until a promise resolves before I return from my function. Basically, I need to perform something synchronously, and JavaScript doesn't seem to like that idea.

Here's a simple example. I have a function that returns a promise, but the promise can't be created until after another promise resolves. The result is my code looks like this:

const lib = require('lib')

var ret_promise
lib.func1().then(() => {
  ret_promise = lib.func2()
})

return ret_promise

The problem is that the outer promise is created, then it immediately moves on to the return, and returns undefined because the then hasn't executed yet. I can't put the return inside the then , because all that will happen is it will return from the interior arrow function.

How do I do this? Is it even possible?

NOTE: I'm using node 6. I can't use async/await

You were close, all you really need to change is return the original promise, and then within it's .then return the second one. The promise returned from the function will then resolve once the second promise resolves.

const lib = require('lib')

var ret_promise = lib.func1().then(() => {
  return lib.func2()
})

return ret_promise

which can be simplified to

const lib = require('lib');

return lib.func1().then(() => lib.func2());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM