【发布时间】:2021-02-05 11:36:54
【问题描述】:
代码:
script1.js:
function getPeople(fetch) {
fetch('some API').then(res => res.json()).then(data => {
return {
count: data.count,
results: data.results
}
})
}
module.exports = getPeople;
脚本2:
const fetch = require('node-fetch');
const getPeople = require('./script1');
getPeople(fetch).then(data => console.log(data) //TypeError: Cannot read property 'then' of undefined
在getPeople 函数中添加return 关键字时,此错误已解决,如下所示:
function getPeople(fetch) {
return fetch('some API').then(res => res.json()).then(data => {
return {
count: data.count,
results: data.results
}
})
}
我想知道为什么我在 fetch() 之前需要这个 return 关键字,而我已经使用它来返回数据:
return {
count: data.count,
results: data.results
}
【问题讨论】:
标签: javascript node.js asynchronous promise