代码:
script1.js:
function getPeople(fetch) {
fetch('some API').then(res => res.json()).then(data => {
return {
count: data.count,
results: data.results
}
})
}
module.exports = getPeople;
script2:
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
}
如果您没有从fetch()
创建的函数中返回promise,那么您的函数只是返回undefined
,并且NOTHING将返回给调用者。你必须兑现承诺。
数据的返回是对.then()
回调的返回。这不是函数的返回。这个返回也是必要的,因为它设置了父promise的解析值,但它只是从回调返回到promise基础结构中,而不是函数本身的返回。要从函数本身返回,需要一个未嵌套在其他函数中的return
。