我想使用Promises以同步顺序执行我的任务,为此,我有以下3个函数:
没有通过'user'变量,它工作正常。我想知道,如何将此“用户”变量传递到我的saveUser.bind()
以运行到我的承诺中并由userSave()
函数保存?
// promise function
function init(fn) {
return new Promise((resolve, reject) => {
fn((err, result) => {
if (err) reject(err);
console.log('the saveUser function ran inside my promise...');
resolve(result);
});
});
}
// saveUser function, need receive the user variable and show in console log
function saveUser(callback, user) {
console.log('1. the user will be save...', user);
setTimeout(() => {
console.log('2. the user was saved!');
return callback(null, true);
}, 1000);
}
// main function that I need to pass the user variable into saveUser() function
let user = {name: 'Rick'};
init(saveUser.bind(x => x)).
then(() => console.log('3. Promise finished with success!')).
catch((err) => console.log('3. Promise was rejected!', err));
答案 0 :(得分:1)
第一个绑定参数是this
绑定代码将如下所示。 saveUser.bind(x=>x, x=>x, user)
// promise function
function init(fn) {
return new Promise((resolve, reject) => {
fn(resolve,reject);
});
}
// saveUser function, need receive the user variable and show in console log
function saveUser(callback, user,resolve,reject) {
console.log('1. the user will be save...', user);
setTimeout(() => {
console.log('2. the user was saved!');
resolve(callback(null, true));
}, 1000);
}
// main function that I need to pass the user variable into saveUser() function
let user = {name: 'Rick'};
init(saveUser.bind(this, x=>x, user)).
then(() => console.log('3. Promise finished with success!')).
catch((err) => console.log('3. Promise was rejected!', err));

答案 1 :(得分:1)
我不确定是否确切地如何整理这个东西,但是在那里,你的代码片段正在工作
// promise function
function init(fn, thisArg, ...params) {
return new Promise((resolve, reject) => {
fn.apply(thisArg, [(err, res) => {
console.log('the saveUser function ran inside my promise...');
}, ...params]).then((data) => {
resolve(data);
}).catch((err) => {
reject(err);
});
});
}
function saveUser(callback, user) {
return new Promise((resolve, reject) => {
console.log('1. saving...');
setTimeout(() => {
console.log('2. the user was saved! user name is ', user.name);
resolve(callback(null, user));
// reject('reason');
}, 200);
});
}
// main function that I need to pass the user variable into saveUser() function
let user = {name: 'Rick'};
init(saveUser, null, user).
then(() => console.log('3. Promise finished with success!')).
catch((err) => console.log('3. Promise was rejected!', err));

如果您不想为此创建新的fn
,您甚至可以在某处保存第一个解析器/拒绝器,或者在调用时将其传递给Promise
。
答案 2 :(得分:0)
init(cb => saveUser(cb, user))
或
将saveUser(callback, user)
更改为saveUser(user, callback)
然后
init(saveUser.bind(this, user))