如何使用异步函数作为另一个函数的默认参数
How would I use an asynchronous function as a default parameter for another function
我正在尝试创建一个函数,如果参数不存在,将调用另一个函数。
例如:function getAllFoo(){
// makes a request to an api and returns an array of all foos
}
function getNumFoo(foosArray = getAllFoo(), num = 5){
// selects num of foos from foosArray or calls getAllFoos then selects num of them
}
尝试用JS Promise包装异步函数,并在依赖函数中调用其then()
函数:
function getAllFoo () {
return new Promise(
// The resolver function is called with the ability to resolve or
// reject the promise
function(resolve, reject) {
// resolve or reject here, according to your logic
var foosArray = ['your', 'array'];
resolve(foosArray);
}
)
};
function getNumFoo(num = 5){
getAllFoo().then(function (foosArray) {
// selects num of foos from foosArray or calls getAllFoos then selects num of them
});
}
function getAllFoo(){
// makes a request to an api and returns an array of all foos
}
function getNumFoo(foosArray = getAllFoo(), num = 5){
// Call getAllFoo() when num is not passed to this function
if (undefined === num) {
getAllFoo();
}
}
可以将async函数包装在promise中。
function promiseGetNumFoo(num) {
return new Promise((resolve, reject) =>
// If there's an error, reject; otherwise resolve
if(err) {
num = 5;
} else {
num = resolve(result);
).then((num) =>
// your code here
)}
相关文章:
- 用嵌套函数和默认函数定义函数
- 在jquery文件上传中调用默认的done函数
- 使用默认js函数的javascript中的日期的第二天
- 如果没有其他函数链接到promise,则默认行为
- 使用默认函数扩展 JavaScript 对象
- 杰辛特 |传递默认设置 |函数声明和“this”
- 如何使用默认函数导出为 commonjs 模块创建类型
- 我可以通过使用函数绑定来保留默认值吗?如果没有,为什么
- 具有默认参数值的 ES6 类构造函数上的 NodeJS 错误
- 函数中的默认值-Javascript
- 如何使用链式函数和默认函数正确返回
- angular-index.html只识别默认路由中定义的函数
- 如何在Javascript匿名函数中提供默认参数
- 在JavaScript中,函数的默认值是多少'的原型属性
- JS恢复默认/全局函数
- 从预防默认函数转义
- 取消绑定 e.prevent默认 从另一个函数转发到链接单击
- 使用默认值定义构造函数.我这样做对吗?
- JavaScript函数默认参数-奇怪的行为
- jQueryUI模式添加函数默认值