[英]Javascript promise pass param into object
var getData = new Promise(function(resolve, reject){
$.post( "data.php", { search: inputData }, function( data ) { //need to pass this
data = $.parseJSON(data);
});
if (data) {
resolve(data);
}
});
this.inputText.on('keyup', function(){
var inputData = this.value; //I need to pass this into object
getData.then(function(fromResolve){
console.log(fromResolve);
}).catch(function(fromReject){
console.log(fromReject);
});
});
I have a jQuery ajax post and I use promise to do something after it post back 我有一个jQuery ajax发布,在发布后我使用promise做点什么
my problem is how can I pass this.value (keyup value)
into promise object, so { search: inputData }
can have value to post 我的问题是如何将
this.value (keyup value)
传递给{ search: inputData }
对象,所以{ search: inputData }
可以有值要发布
Make getData()
and actual function, so it can take parameters. 使用
getData()
和实际函数,以便可以使用参数。
jQuery's post()
already returns a promise, so you don't need to wrap again. jQuery的
post()
已经返回了promise,因此您无需再次包装。
function getData( inputData ) {
return $.post( "data.php", { search: inputData } );
}
this.inputText.on('keyup', function(){
var inputData = this.value;
getData( inputData )
.then(function(fromResolve){
console.log(fromResolve);
}).catch(function(fromReject){
console.log(fromReject);
});
});
Simply call resolve
from the jQuery callback function. 只需从jQuery回调函数调用
resolve
。
var getData = new Promise(function(resolve, reject){
$.post( "data.php", { search: inputData }, function( data ) { //need to pass this
data = $.parseJSON(data);
if (data) { resolve(data); }
else { reject(); }
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.