내부에 JavaScript 함수를 정의 할 수있는 JSON과 같은 구성이 있습니다. 이제 해당 함수 배열을 가져와 실행하는 실행 함수가 있습니다. 어떻게 할 수 있습니까?
const listOfFuncs = [
{
"func1": (...args) => console.log(...args)
},
{
"func2": async (...args) => {
return await fetch('some_url');
}
}
]
function execute() {
// how to execute the above array of functions now ?
}
// Should this be called as await execute()?
execute();
한 기능 동기화 및 다른 기능을 async
& awai
t 로 볼 수 있습니다 . 모든 기능을 async
& 로 정의하는 것이 await
나쁘게 보입니다 (많은 새로운 약속 생성) + 모든 기능을 동기식으로 정의 할 수도 없습니다.
미리 답변 해 주셔서 감사합니다.
Promise.all()
약속 배열을 해결하는 데 사용할 수 있습니다 .
약속 이외의 값은있는 그대로 반환됩니다.
const listOfFuncs = [
() => 45,
async () => new Promise(resolve => {
setTimeout(() => resolve(54), 100);
})
];
async function execute() {
return Promise.all(listOfFuncs.map(func => func()));
}
// execute() will return a Promise which resolves to an array
// containing all results in the same order as the functions.
execute().then(result => console.log(result));
// Logs: [45, 54] after 100ms
프라 미스가 포함 된 객체를 해결하는 기본 함수는 없지만 일부 라이브러리는 더 복잡한 패턴 (취소, 레이스 등)을 더 쉽게 사용할 수 있도록 대체 Promise API를 구현합니다. 가장 잘 알려진 것은 Bluebird입니다.
Promise.props
원하는 작업을 거의 수행 하는 메소드를 구현합니다 . http://bluebirdjs.com/docs/api/promise.props.html
var Promise = require("bluebird");
Promise.props({
pictures: getPictures(),
comments: getComments(),
tweets: getTweets()
}).then(function(result) {
console.log(result.tweets, result.pictures, result.comments);
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다