属性 .then 未定义的错误
Property .then undefined error
我在下面的 checkB 函数中不断收到 .then 未定义错误。
export function checkB(accountId) {
return new Promise((resolve, reject) => {
const myRepo = new myRepo();
myRepo.checkC(accountId).then( results => {
return resolve(results));
});
});
}
我可以调用 checkC 并得到 json 响应。
checkC(){
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
fetchApi.get(url).then(results => {
return results.json().then(json => {
return json;
});
}).catch(err => {
console.log(err);
});
}
我有一个调用 CheckB 的初始函数 checkA() - 我正在尝试在 CheckA 中同步获取结果,但将 运行 保留在 CheckB 的 .then 未定义错误中。
任何人都可以解释我在这里做错了什么。
您需要 return 来自 checkC()
的 Promise:
checkC(){
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
return fetchApi.get(url)
.then(results => results.json());
.catch(console.log);
}
此外,由于 results.json()
是 return 的 结果 的 Promise,您不需要执行 .then(json => {return json;});
事情。
而且,更一般地说,如果您需要对一个承诺的结果做某事,而这个承诺本身就是另一个承诺的结果,您可以将它们链接起来而无需嵌套代码。
你可以这样写你的第二个例子(这是没用的,我写的第一个代码工作正常,只是为了一个例子):
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
fetchApi.get(url).then(results => {
return results.json();
})
.then(json => {
return json;
}).catch(err => {
console.log(err);
});
我在下面的 checkB 函数中不断收到 .then 未定义错误。
export function checkB(accountId) {
return new Promise((resolve, reject) => {
const myRepo = new myRepo();
myRepo.checkC(accountId).then( results => {
return resolve(results));
});
});
}
我可以调用 checkC 并得到 json 响应。
checkC(){
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
fetchApi.get(url).then(results => {
return results.json().then(json => {
return json;
});
}).catch(err => {
console.log(err);
});
}
我有一个调用 CheckB 的初始函数 checkA() - 我正在尝试在 CheckA 中同步获取结果,但将 运行 保留在 CheckB 的 .then 未定义错误中。
任何人都可以解释我在这里做错了什么。
您需要 return 来自 checkC()
的 Promise:
checkC(){
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
return fetchApi.get(url)
.then(results => results.json());
.catch(console.log);
}
此外,由于 results.json()
是 return 的 结果 的 Promise,您不需要执行 .then(json => {return json;});
事情。
而且,更一般地说,如果您需要对一个承诺的结果做某事,而这个承诺本身就是另一个承诺的结果,您可以将它们链接起来而无需嵌套代码。
你可以这样写你的第二个例子(这是没用的,我写的第一个代码工作正常,只是为了一个例子):
const fetchApi = new FetchApi();
const url = `${config.routes.base}/mypath/5`;
fetchApi.get(url).then(results => {
return results.json();
})
.then(json => {
return json;
}).catch(err => {
console.log(err);
});