我必须将多个用户数据发送到一个外部API,这不支持批量插入。所以我循环它并多次调用我的节点API,但收到错误。 [在此输入图像说明] [1]
/ calling api from service
var testArry = [
{"name":"name1","id":"1" },
{"name":"name2","id":"2" },
{"name":"name3","id":"3" }
];
myAPIFunction(testArry).then(function (status) {
console.log("Success: ", status);
}).catch(function (err) {
console.log("ERROR : ", err);
})
// API Function
function myAPIFunction(options) {
for (var i in options) {
return new Promise((resolve, reject) => {
axios({
method: "post",
url: `https:test/url`, // External API to save data
data: options[i].data
}).then(function (err, res) {
console.log("Success : Promise is resolved");
Promise.resolve(res.data);
}).catch(function (err) {
console.log("ERROR : Promise is rejected ");
})
});
} // End of loop
}
错误:
ERROR : TypeError: Cannot read property 'then' of undefined
at C:\Users\IBM_ADMIN\git\PayGo\L1SupportAPI\routes\onboarding\index.js:141:55
at nextTask (C:\Users\IBM_ADMIN\git\PayGo\L1SupportAPI\node_modules\async\dist\async.js:5310:14)
at next (C:\Users\IBM_ADMIN\git\PayGo\L1SupportAPI\node_modules\async\dist\async.js:5317:9)
at C:\Users\IBM_ADMIN\git\PayGo\L1SupportAPI\node_modules\async\dist\async.js:958:16
at C:\Users\IBM_ADMIN\git\PayGo\L1SupportAPI\routes\onboarding\index.js:98:17
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:1284) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already
called.
(node:1284) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a non-zero exit code.
ERROR : Promise is rejected
ERROR : Promise is rejected
答案 0 :(得分:2)
你没有从那个函数返回任何东西,因此。然后就不存在了。
此外,你不必创造新的承诺,呼叫axios本身就是承诺:
var testArry = [
{"name":"name1","id":"1" },
{"name":"name2","id":"2" },
{"name":"name3","id":"3" }
];
myAPIFunction(testArry).then(function (status) {
console.log("Success: ", status);
}).catch(function (err) {
console.log("ERROR : ", err);
})
// API Function
function myAPIFunction(options) {
const promises = [];
for (var i in options) {
const promise = axios({
method: "post",
url: `https:test/url`,
data: options[i].data
}).then(function (res) {
console.log("Success : Promise is resolved");
return res;
}).catch(function (err) {
console.log("ERROR : Promise is rejected ");
})
promises.push(promise)
}
return Promise.all(promises);
}
我试图在网址设置为http://google.com的情况下运行它并收到此输出:
ERROR : Promise is rejected
ERROR : Promise is rejected
ERROR : Promise is rejected
Success: [ undefined, undefined, undefined ]
哪个是正确的,google.com不接受POST