简体   繁体   English

数据来自另一个调用后,在Node.js服务器中解决Promise?

[英]Resolving promise in nodejs server after data comes from another call?

I have a few promises in my node server that after they all resolve the server renders to the client. 我在节点服务器中有一些承诺,在它们全部解决后,服务器会将其呈现给客户端。 I am using Promise.all([ ... that has all the data from the few promises I have. 我正在使用Promise.all([ ...包含了我的一些诺言中的所有数据。

I now however need some data from another call before one of my promises resolves. 但是,在我的一个诺言解决之前,我现在需要来自另一个呼叫的一些数据。 But it seems Promise.all is still resolving before I have what I need. 但是Promise.all似乎仍在解决我需要的东西之前。

const myPromise = new Promise((resolve) => {
    needDataFromThisCall(someInfo)
    .then((data) => {
        return resolve(sortData(data))
    })
    .catch((error) => {
        //error handle
    })
})
.then((resolvedData) => {
    return resolvedData;
})

This does not seem to work because the final .then the resolvedData is undefined and seems to get resolved before I get into my sortData function. 这似乎不是因为最后的工作.then在resolvedData是undefined ,似乎之前,我进入我得到解决sortData功能。 Does the return resolve(sortData... not end up giving its return value to the final .then ? return resolve(sortData...最终不会将其返回值提供给最终的.then吗?

How should this really be done so myPromise can resolve after I have that data needed to send to sortData ? 我该如何真正做到这一点,以便myPromise在将数据发送到sortData之后可以解析?

Below code works fine. 下面的代码工作正常。 Assuming sortData is synchronous function, you need to resolve myPromise to get the result. 假设sortData是同步函数,则需要解析myPromise以获得结果。

 let someInfo = [2,3,1]; let needDataFromThisCall = info => new Promise(res => setTimeout(()=>res(info), 500) ); let sortData = data => data.sort(); const myPromise = new Promise((resolve) => { needDataFromThisCall(someInfo) .then((data) => { return resolve(sortData(data)) }) .catch((error) => { //error handle }) }) .then((resolvedData) => { return resolvedData; }) myPromise.then(data => console.log('final data', data)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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