gpt4 book ai didi

node.js - NodeJS/请求 promise : the promise is resolved automatically

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:00 26 4
gpt4 key购买 nike

我使用 request-promise Node 模块如下:

let rp = require('request-promise');

我有以下 promise 链:

getData().then( data => {
return getUser(data);
})
.then( data => {
return getProfiles(data);
}).then( data => {
updateAddresses(data);
});

updateAddresses 如下:

function updateAddresses(data){
var promises = data.map( (aProfile) => {
var options = {url:'http://example.com', method:'POST'};
return rp(options);
});

// Promise.all(promises).then(...);
}

所以我正在为数组的每个元素准备一个 promise (请求 promise )。

问题是,即使我删除 Promise.all ,这些 promise 也会触发!

这怎么可能?我怎样才能让 promise 不被解雇?

问候。

最佳答案

您的 updateAddresses 没有返回任何可调用 then() 的内容,并且您也没有等待 updateAddress 的结果。

function updateAddresses(data){
var promises = data.map( (aProfile) => {
var options = {url:'http://example.com', method:'POST'};
return rp(options);
});

//Return something to then()
return Promise.all(promises).then(...);
}

然后等待:

getData().then( data => {
return getUser(data);
})
.then( data => {
return getProfiles(data);
}).then( data => {
return updateAddresses(data);
}).then(e => somethingelse);
<小时/>

根据您的要求存储映射ped地址对象:

function updateAddresses(data) {
return data.map((aProfile) => {
return {
url: 'http://example.com',
method: 'POST'
}
});
}

getData()
.then(data => getUser(data))
.then(data => getProfiles(data))
.then((data) => {
let addressOptions = updateAddresses(data);
/*
* You now have an Array of Objects of the form:
* {
* url: "",
* method: "",
* }
*/
return Promise.resolve(addressOptions);
})
.then(addressOptions => Promise.all(addressOptions.map(address => rp(address))))
.then((arrayOfResolvedData) => {
/*
* arrayOfResolvedData is an Array of data per whatever rp() returns
* probably Response Objects
*/
console.log(arrayOfResolvedData);
})

关于node.js - NodeJS/请求 promise : the promise is resolved automatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45445577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com