承诺返回未定义 [英] Promise returning undefined
本文介绍了承诺返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 promise 向 php 脚本发送 ajax 请求,该脚本检查服务器上是否存在文件并返回布尔值.
I am trying to use promise to send an ajax request to a php script which checks if a file exist on the server and returns a boolean value.
我有以下代码,但 fileExists 函数总是返回 undefined.
I have the below code but the fileExists function always return undefined.
如何将 promise 包装在函数中并让函数返回 promise 值?
How can I wrap the promise in a function and have the function return the promise value?
function fileExists(url) {
var promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
promise.then(function(e) {
return e;
});
}
var result = fileExists("url_to_file");
推荐答案
function fileExists(url) {
return promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}
var result = fileExists("url_to_file").then(foo());
试试这个.
你的函数什么都不返回.如果您返回承诺,您可以在数据解决后保留数据.
your function returns nothing . If you return the promise you can hold on to the data once its resolved.
这篇关于承诺返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文