I have to write async function for:
const myAsyncFunction = async(function* (promise) {
const data = yield promise;
console.log(data);
});
myAsyncFunction(Promise.resolve("Hello world")); // console: ‘Hello world!’`
result should be - console: ‘Hello world!’
I thought it would be a right implementation:
function async(cb) {
return cb().next();
}
const myAsyncFunction = async(function* (promise) {
const data = yield promise;
console.log(data);
});
myAsyncFunction(Promise.resolve("Hello world")); // console: ‘Hello world!’`
but I nave a type error: TypeError: myAsyncFunction is not a function
I found some example generator forwards with the results of any promises it has yielded
but I cannt understand how it works and where is my mistake:
function async(cb) {
return function () {
let generator = cb.apply(this, arguments);
function handle(result) {
if (result.done) return Promise.resolve(result.value);
return Promise.resolve(result.value).then(
function (res) {
return handle(generator.next(res));
},
function (err) {
return handle(generator.throw(err));
}
);
}
};
}
please, explain what Im doing wrongly?
I'm assuming your code (mwe) looks like this:
And when you run it, you do indeed get the error
TypeError: myAsyncFunction is not a function. However, when you adjust to use the copied function from the article:You don't get the error. This is because the code from the article returns a function in the async definition, and thus you are able to apply it with the args given in the line
In your original defintion, the
asyncdefinition does not return a function so the invocation above fails.Following on from your next post, and trying to understand what you want, the following will print the string using the console line in the generator function, but still not quite sure what it is you are trying to achieve: